//
//  EMMHousingViewController.m
//  EMMApp
//
//  Created by Mac on 16/6/27.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMHousingViewController.h"

/** ViewController
 *
 *  ViewController导入.h文件
 */
#import "MarketingViewController.h"
#import "MHPhotoBrowserController.h"
#import "ProjectModel.h"

/** View
 *
 *  首页View导入.h文件
 */
#import "EMMImageView.h"

/** Cell
 *
 *  首页Cell导入.h文件
 */
#import "EMMHousingCell.h"
#import "HousingCVCell.h"

/** Api
 *
 *  首页Api调用导入.h文件
 */
#import "GetHousesListApi.h"


@interface EMMHousingViewController ()<UITableViewDelegate,
                                        UITableViewDataSource,
                                        DateCollectionViewCellDelegate>

/**
 *  判断导航
 */
@property (nonatomic, assign) BOOL isShowUI;

/**
 *  导航栏
 */
@property (nonatomic, strong) MenuLitsView *menuD;

/**
 *  导航数组(名字数组)
 */
@property (nonatomic, strong) NSMutableArray *menuListD;

/**
 *  导航数组(项目对象)
 */
@property (nonatomic, strong) NSMutableArray *menuArrD;

/**
 *  创建UITableView
 */
@property (nonatomic, strong) UITableView *housingTableView;


/*
 项目列表对象（包含图片数组和楼盘数组）
 */
@property (nonatomic, strong) GetHousesList *getHousesList;

/*
 项目列表
 */
@property (nonatomic, strong) NSMutableArray *dataArr;

/*
 项目列表下 每个楼栋信息对象数组（二维数组）
 */
@property (nonatomic, strong) NSMutableArray *subDataArr;

/*
 项目展示图片数组
 */
@property (nonatomic, strong) NSMutableArray *flatMapList;

@end

@implementation EMMHousingViewController

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    [self tabelShowUI];
}

#pragma mark - 初始化UITableView
- (void)tabelShowUI {
    _housingTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight-SafeAreaBottomHeight) style:UITableViewStylePlain];
    _housingTableView.delegate = self;
    _housingTableView.dataSource = self;
    _housingTableView.backgroundColor = [UIColor colorFromHexCode:@"#f7f7f7"];
    _housingTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _housingTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_housingTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - 生命周期函数调用方法
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[EMMAppChecker sharedInstance] startCheckVgoUpdate];
    _menuListD = [[NSMutableArray alloc] init];
    _menuArrD = [[NSMutableArray alloc] init];
    _dataArr = [[NSMutableArray alloc] init];
    _subDataArr = [[NSMutableArray alloc] init];
    _flatMapList = [[NSMutableArray alloc] init];
    [self creatProjectListApi];
    [self postGetHousesListApi];
    [self creatNavigationController];
}

#pragma mark - 切换项目IAP
/**
 *  功能描述：
 *  切换项目的读取本地存储的数据
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 *
 *  修改描述：修改方法的命名
 *  修改时间：2016/12/26
 *  修改人：wangguiping
 */
- (void)creatProjectListApi {
    [_menuArrD removeAllObjects];
    [_menuListD removeAllObjects];
    NSUserDefaults *us = [NSUserDefaults standardUserDefaults];
    NSMutableArray *projectDataArray = [us objectForKey:@"projectArray"];
    if (projectDataArray.count > 0 ) {
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        for (int i = 0; i < projectDataArray.count; i++) {
            NSData *data = projectDataArray[i];
            ProjectModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            [_menuListD addObject:model.projectName];
            ProjectList *lsit = [[ProjectList alloc] init];
            lsit.projectName = model.projectName;
            lsit.projectId = model.projectId;
            lsit.projectCode = model.projectCode;
            [_menuArrD addObject:lsit];
            [arr addObject:lsit.projectCode];
        }
        NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
        NSString *projectCode = [userdf objectForKey:@"projectCode"];
        for (int i = 0; i < arr.count; i++) {
            NSString *pro = [arr objectAtIndex:i];
            if ([pro isEqualToString:projectCode]) {
                [userdf setObject:[NSString stringWithFormat:@"%d",i] forKey:@"indexString"];
                [userdf synchronize];
            }else {
            }
        }
    }
}

#pragma mark - 房源数据请求
/**
 *  功能描述：
 *  切换项目的读取本地存储的数据
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 *
 *  修改描述：新增Api请求查询到项目权限变更重新登录的唯一标识
 *  修改时间：2016/12/30
 *  修改人：wangguiping
 */
- (void)postGetHousesListApi {
    [self showHudInWindow:@"正在加载请稍等......"];
    [_dataArr removeAllObjects];
    [_subDataArr removeAllObjects];
    [_flatMapList removeAllObjects];
    GetHousesListApi *api = [[GetHousesListApi alloc] initWith];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetHousesListApi *result = (GetHousesListApi *)request;
        if (result.isSuccess) {
            GetHousesList *get = result.resultData;
            _getHousesList = get;
            NSLog(@"----> %@",_getHousesList);
            for (PremisesList *list in _getHousesList.premisesList) {
                [_dataArr addObject:list];
                NSMutableArray *arr = [[NSMutableArray alloc] init];
                for (BuildingList *bList in list.buildingList) {
                    [arr addObject:bList];
                }
                [_subDataArr addObject:arr];
            }
            for (FlatMapList *list in _getHousesList.flatMapList) {
                [_flatMapList addObject:list.flatMapUrl];
            }
            [_housingTableView reloadData];
        } else {
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [_housingTableView reloadData];
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark - 创建导航
/**
 *  功能描述：
 *  导航初始化
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)creatNavigationController {
    [self updateNavBar];
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *token = [userdf objectForKey:@"is_login"];
    NSString *projectName;
    if ([NSString isStringEmpty2:token] == NO) {
        projectName  = [userdf objectForKey:@"projectName"];
    }
    NavigationView *view = [[NavigationView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH/2, 44) title:projectName colo:@"2"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button addTarget:self action:@selector(showPopover:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, view.frame.size.width, 44.0);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    button.tag = 101;
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [view addSubview:button];
    [self.navigationItem setTitleView:view];
    
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"ico_pict"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(housRightClick:)];
    [self.navigationItem setRightBarButtonItem:rightItme];
}

#pragma mark - 导航右按钮点击事件调用方法
/**
 *  功能描述：
 *  导航右按钮触发的方法调用
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)housRightClick:(UIButton *)btn {
    if (_flatMapList.count > 0) {
        NSLog(@"%@",_flatMapList);
        MHPhotoBrowserController *vc = [MHPhotoBrowserController new];
        NSMutableArray * bigImgArray = [NSMutableArray new];
        for (int i = 0; i < _flatMapList.count; i++) {
            NSString *url = [_flatMapList objectAtIndex:i];
            NSString *url1 = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
             [bigImgArray addObject:[MHPhotoModel photoWithURL:[NSURL URLWithString:url1]]];
        }
        vc.currentImgIndex = 0;
        vc.displayTopPage = YES;
        vc.displayDeleteBtn = YES;
        vc.imgArray = bigImgArray;
        vc.displayDeleteBtn = NO;
        [self presentViewController:vc animated:YES completion:nil];
        [vc setMHPhotoBrowserBlock:^(NSInteger inde) {
            [_flatMapList removeObjectAtIndex:inde];
            NSLog(@"%@",_flatMapList);
        }];
    }else {
        [self showToast:@"暂无图片预览"];
    }
}

#pragma mark - 显示app商家列表
/**
 *  功能描述：
 *  是否显示选择项目列表界面
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)showPopover:(UIButton *)button {
    if (_isShowUI == YES) {
        [self removeMenuLitsViewSubView];
        [self creatView];
        _isShowUI = NO;
    }else {
        [self removeMenuLitsViewSubView];
        _isShowUI = YES;
    }
}

#pragma mark - 导航栏弹出项目菜单
/**
 *  功能描述：
 *  项目列表界面初始化
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)creatView {
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *num = [userdf objectForKey:@"indexString"];
    NSInteger h = 0;
    if (_menuListD.count > 6) {
        h = 6*50;
    }else {
        h = _menuListD.count *50;
    }
    _menuD = [[MenuLitsView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight) items:_menuListD indet:num isShowUI:YES guodu:h];
    _menuD.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:_menuD];
    __weak MenuLitsView *weakSelf = _menuD;
    [weakSelf setMenuLitsBlock:^(NSString *title, NSString *indet) {
        if ([NSString isStringEmpty2:title] == NO) {
            _isShowUI = YES;
        }else {
            _isShowUI = YES;
        }
        if ([NSString isStringEmpty2:indet] == NO) {
            ProjectList *lsit1 = _menuArrD[[indet intValue]];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            [userdf setObject:lsit1.projectCode forKey:@"projectCode"];
            [userdf setObject:lsit1.projectId forKey:@"projectId"];
            [userdf setObject:lsit1.projectName forKey:@"projectName"];
            [userdf setObject:indet forKey:@"indexString"];
            [userdf synchronize];
            [self creatNavigationController];
            [self postGetHousesListApi];
            [[MerchantResourceVModel merchantResourceVModel] startMerchantResourceVModel];
        }
        [weakSelf removeFromSuperview];
    }];
}

#pragma mark - 移除导航菜单
/**
 *  功能描述：
 *  删除项目选择界面
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)removeMenuLitsViewSubView {
    [_menuD removeFromSuperview];
    _menuD = nil;
}

#pragma mark - UITableView 代理
/**
 *  功能描述：
 *  UITabelView 代理的方法调用
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PremisesList *list = [_dataArr objectAtIndex:indexPath.row];
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for (BuildingList *bList in list.buildingList) {
        [arr addObject:bList];
    }
    float h = arr.count/4.00;
    return 50+60*ceilf(h);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellId = @"EMMHousingCellId";
    EMMHousingCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"EMMHousingCell" owner:self options:nil] lastObject];
    }
    cell.backgroundColor = [UIColor colorFromHexCode:@"f6fafb"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49.5, EMM_WIDTH, 0.5)];
    imageView.backgroundColor = [UIColor colorFromHexCode:@"#dbeded"];
    [cell addSubview:imageView];
    if (_dataArr.count > 0) {
        PremisesList *list = [_dataArr objectAtIndex:indexPath.row];
        cell.titleLabel.text = list.premisesName;
        cell.kyNumLabel.text = list.notSoldNum;
        cell.ysNumLabel.text = list.soldNum;
        cell.delegate = self;
        [cell initWithNSMutableArray:_subDataArr  indexNum:indexPath.row];
        [cell.homeCollectionView reloadData];
    }
    return cell;
}
 
#pragma mark - DateCollectionViewCellDelegate 点击楼栋代理方法
-(void)didSelectedTableview:(NSInteger )index withcollecttion:(NSIndexPath *)collectionindex{
    NSLog(@"----%ld ---%ld",index,collectionindex.row);
    if (_dataArr.count > 0) {
        PremisesList *list = [_dataArr objectAtIndex:index];
        NSMutableArray *arr = [[NSMutableArray alloc] init];
        for (BuildingList *bList in list.buildingList) {
            [arr addObject:bList];
        }
        BuildingList *bList = [arr objectAtIndex:collectionindex.row];
        MarketingViewController *evc = [[MarketingViewController alloc] init];
        evc.hidesBottomBarWhenPushed = YES;
        evc.premisesId = bList.premisesId;
        evc.buildingId = bList.buildingId;
        [self.navigationController pushViewController:evc animated:YES];
    }
}

@end
